import { Component, OnInit, Output, EventEmitter , ViewChild, OnDestroy, AfterViewInit, ElementRef, Renderer2 } from '@angular/core';
import { FormBuilder, Validators, FormControl } from '@angular/forms';

import { SafetyInterface } from 'src/app/config/shared/safety-helmet/SafetyInterface';
import { TipsService } from 'src/app/tips/tips.service';
import { isNumberJudge } from 'src/app/shared/validators/benumber.directive';
import { isPString32 } from 'src/app/shared/validators/pstring32.directive';
import { IeCssService } from 'src/app/shared/func-service/ie-css.service';

import Logger from 'src/app/logger';



@Component({
  selector: 'app-helmet-config',
  templateUrl: './config.component.html',
  styleUrls: ['./config.component.scss']
})
export class HelmetConfigComponent implements OnInit, AfterViewInit, OnDestroy {

  @ViewChild('player', {static: true}) playerChild: any;
  @ViewChild('player', {read: ElementRef}) playerDom: ElementRef;

  @Output() private onSubmitOutput = new EventEmitter();  

  constructor(
    private fb: FormBuilder,
    private el: ElementRef,
    private Re2: Renderer2,
    private tips: TipsService,
    private ieCss: IeCssService,
  ) { }
  private logger: Logger = new Logger('helmet-config');

  private viewInit: boolean = false;
  private src = '';
 


  playerOption = {
    isReshape: false,
    speName: 'helmet-config'
  };

  Form = this.fb.group({
    sUrl: ['', Validators.required],
    iFraction:  [50 , [Validators.required, Validators.min(0), Validators.max(100), isNumberJudge]],
    iInterval:  [10 , [Validators.required, Validators.min(0), Validators.max(300), isNumberJudge]]
  });

  oldForm = {
    sUrl: NaN,
    iFraction: NaN,
    iInterval: NaN,
  };


  get sUrl(): FormControl {
    return this.Form.get('sUrl') as FormControl;
  }

  get iFraction(): FormControl {
    return this.Form.get('iFraction') as FormControl;
  }

  get iInterval(): FormControl {
    return this.Form.get('iInterval') as FormControl;
  }

  ngOnInit(): void {
    
  }

  ngAfterViewInit() {
    this.playerChild.hideBigPlayBtn();
    this.viewInit = true;
  }

  ngOnDestroy() {
    try {
      this.playerChild.diyStop();
    } catch {}
    this.playerChild.destroyWhenSwitch();
  }

 
  onSubmit() {
   this.onSubmitOutput.emit();
  }

  onContentChange(change: number, name: string) {
   
    if (!isNaN(this.oldForm[name]) && Number(change) !== this.oldForm[name] && !isNaN(Number(change))) {
      change = Number(change);
      this.oldForm[name] = change;
      this.Form.get(name).setValue(change);
    } else if (isNaN(Number(change)) && !isNaN(this.oldForm[name])) {
      this.Form.get(name).setValue(this.oldForm[name]);
    } else if (isNaN(this.oldForm[name])) {
      this.oldForm[name] = change;
    }
  }

  onContentTextChange(change: string, name: string) {
    if (change!== this.oldForm[name]) {
      this.oldForm[name] = change;
      this.Form.get(name).setValue(change);
    }
  }

  getConfigInfo() {
    return this.Form.value;
  }

  playEntry() {
    if (this.viewInit && this.src) {
      this.playerChild.displayUrl = this.src;
      this.playerChild.bigBtnPlay();
    }
  }

  pausePlayer() {
    if (this.viewInit && this.playerChild) {
    this.playerChild.diyPause();
    }
  }

  stopPlayer() {
    if (this.viewInit && this.playerChild && this.playerChild.isPlaying) {
      this.playerChild.diyStop();
    }
  }

  resizePlayer() {
    this.playerChild.reshapeCanvas();
  }

  initComponent(initInfo: SafetyInterface, url: string) {
    this.Form.patchValue(initInfo);
    this.src = url;
    this.waitViewInit(5000)
      .then(() => {
        this.playEntry();
      })
      .catch((error) => {
        this.logger.error(error, 'initComponent:waitViewInit:');
        this.tips.setRbTip('initFailFreshPlease');
      });
  }

  waitViewInit = (timeoutms: number) => new Promise(
    (resolve, reject) => {
      const isViewInitComplete = () => {
        timeoutms -= 100;
        if (this.viewInit) {
          resolve();
        } else if (timeoutms <= 0) {
          reject();
        } else {
          setTimeout(isViewInitComplete, 100);
        }
      };
      isViewInitComplete();
    }
  )

}
